package ui;

import game.Launch;
import header.MapHandler;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.event.*;

import map.Launcher;

// Shows file list for loading maps and starting the game.
public class FileList {

	JFrame frame;
	JScrollPane listScroll;
	JList list;
	MapHandler map;
	String name;
//	Game game;
	
	public FileList() {
		frame = new JFrame();
		JPanel south = new JPanel();
		JLabel name = new JLabel("Select file");
		DefaultListModel listModel = new DefaultListModel();
		list = new JList(listModel);
		listScroll = new JScrollPane(list);
		frame.getContentPane().add(BorderLayout.NORTH, name);
	//	String workDir = System.getProperty("user.dir");
	//	File dir = new File(workDir);
		File dir = new File(".");
		File[] flist = dir.listFiles();
		for(File f : flist) {
			if(f.isFile())
				listModel.addElement(f);
		}
		list.addListSelectionListener(new listSelect());
		frame.getContentPane().add(BorderLayout.CENTER, listScroll);
		JButton edit = new JButton("Edit");
		JButton start = new JButton("Start Game");
		south.add(edit);
		south.add(start);
		edit.addActionListener(new editActionListener());
		start.addActionListener(new startListener());
		frame.getContentPane().add(BorderLayout.SOUTH, south);
		frame.setSize(250, 250);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
	}
	
	class editActionListener implements ActionListener {
		@SuppressWarnings("unused")
		public void actionPerformed(ActionEvent e) {
			frame.setVisible(false);	
			frame.dispose();
			Launcher l = new Launcher(name);
			l.go();
		}
	}
	
	class startListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			frame.setVisible(false);
			frame.dispose();
			Launch l = new Launch();
			l.fix();
		//	l.map();
		//	l.frame();
			
		}
	}
	
	class listSelect implements ListSelectionListener {
		public void valueChanged(ListSelectionEvent ev) {
			if(!ev.getValueIsAdjusting()) {
				System.out.println("Selected value is: " + list.getSelectedValue().toString());
				name = list.getSelectedValue().toString();
				System.out.println(name);
				name = name.substring(2);
				System.out.println(name);
			}
		}
	}
}
